package indi.mumu.common.controller;

import java.util.ArrayList;
import java.util.List;

import com.jfinal.aop.Before;
import com.jfinal.core.Controller;
import com.jfinal.plugin.activerecord.Db;

import indi.mumu.common.model.Clothes;
import indi.mumu.common.model.Saleorder;
import indi.mumu.common.model.Saleorderitem;
import indi.mumu.interceptor.POSInterceptor;
import indi.mumu.service.SaleOrderItemService;
import indi.mumu.service.SaleOrderService;
import indi.mumu.validator.POSValidator;
import indi.mumu.validator.SaleValidator;

public class SaleOrderController extends Controller{

	private SaleOrderService service = new SaleOrderService();
	private String saleOrderId;
	
	public void index() {
		setAttr("saleOrderPage", Saleorder.dao.paginate(getParaToInt(0, 1), 10, "select *","from saleorder"));
		render("sell.html");
	}
	
	public void getClothesByBarcode(){
		String key = getPara("key");
		setAttr("clothesPage", Clothes.dao.paginate(getParaToInt(0, 1), 10, "select *", "from clothes where barcode=" + key));
		setAttr("barcode",key);
		render("addsaleorder.html");
	}
	
	/**
	 * 添加一条新订单
	 */
	public void addSaleOrder() {
		
		Saleorder saleOrder = getModel(Saleorder.class);
		service.addSaleOrder(saleOrder);
		render("search.html");
		
	}

	public void addGoods() {

		String saleOrderIdSql = "select * from saleorder where id=(select max(id) from saleorder)";
		String saleOrderId = Saleorder.dao.find(saleOrderIdSql).get(0).getSaleorderId();
		
		String productId = getPara("productId");
		String price = getPara("price");
		String count = getPara("count");
		String total = String.valueOf(Double.valueOf(price) * Integer.valueOf(count));
		System.out.print("count"+count+"saleOrderId"+this.saleOrderId+"productId"+productId+"price"+price);
		
		String sql = "UPDATE saleorder SET Total = Total + " + total + " WHERE saleOrder_id = " + saleOrderId;
		Db.update(sql);
		
		Saleorderitem saleOrderItem = getModel(Saleorderitem.class);
		saleOrderItem.setCount(Integer.valueOf(count));
		saleOrderItem.setProductId(productId);
		saleOrderItem.setSaleorderId(saleOrderId);
		
		SaleOrderItemService saleOrderItemService = new SaleOrderItemService();
		saleOrderItemService.addItem(saleOrderItem);
		
		setAttr("saleOrderItemPage", Saleorderitem.dao.paginate(getParaToInt(0, 1), 10, "select *","from saleorderitem where saleOrder_id=" + saleOrderId));
		render("saleorderitem.html");
	}

	/**
	 * 编辑订单
	 */
	public void edit(){
		String saleOrderId = getPara("saleOrderId");
		setAttr("saleOrderItemPage", Saleorderitem.dao.paginate(getParaToInt(0, 1), 10, "select *","from saleorderitem where saleOrder_id=" + saleOrderId));
		render("saleorderitem.html");
	}
	
	@Before(SaleValidator.class)
	public void update() {
		getModel(Saleorder.class).update();
		redirect("/sell");
	}
	
	public void delete(){
		Saleorder.dao.deleteById(getParaToInt());
		redirect("/sell");
	}
}
